package com.fionera.sample.fragment

import android.content.Intent
import android.support.v7.widget.GridLayoutManager
import android.text.TextUtils
import android.view.View
import com.fionera.sample.R
import com.fionera.sample.activity.StampActivity
import com.fionera.sample.adapter.RvStampListAdapter
import com.fionera.sample.bean.StampListBean
import com.fionera.sample.constant.UrlConstants
import com.fionera.sample.util.OkHttpUtil
import com.fionera.sample.util.ShowToast
import com.google.gson.Gson
import kotlinx.android.synthetic.main.fragment_stamp_list.*
import java.util.*

/**
 * @author fionera
 */
class StampListFragment : TitleBarFragment() {

    private var stampListBean: StampListBean? = null
    private val stampList = ArrayList<StampListBean.RowsEntity>()

    override fun setLayoutResource() = R.layout.fragment_stamp_list

    override fun findViewInThisFunction(rootView: View) {
        setTitleBarText("用印")
        setTitleBarLeft(R.drawable.ic_action_back)
        setTitleBarLeftClick(View.OnClickListener {
            mActivity.finish()
        })

        initData()
    }

    private fun initData() {
        rv_stamp_list.layoutManager = GridLayoutManager(mContext, 1)
        val adapter = RvStampListAdapter(mContext, stampList)
        rv_stamp_list.adapter = adapter
        adapter.setOnButtonClickListener { _, pos, type ->
            when (type) {
                0 -> clickToStamp(pos)
                else -> {
                }
            }
        }

        sendRequestToGetStampList()
    }

    private fun sendRequestToGetStampList() {
        mProcessDialog.showWithCancel()
        getEnqueue(String.format(Locale.CHINA, UrlConstants.STAMP_LIST, 0),
                object : OkHttpUtil.NetCallBack {

                    override fun onSucceed(json: String) {
                        mProcessDialog.dismiss()
                        stampListBean = Gson().fromJson(json, StampListBean::class.java)
                        stampList.addAll(stampListBean!!.rows)
                        rv_stamp_list.adapter.notifyDataSetChanged()
                    }

                    override fun onFailed(reason: String) {
                        mProcessDialog.dismiss()
                        ShowToast.shortTime(reason)
                    }
                })
    }

    private fun clickToStamp(pos: Int) {
        if (TextUtils.equals(stampList[pos].applyType, "COUNT_LIMIT")) {
            val intent = Intent(mContext, StampActivity::class.java)
            intent.putExtra("sealApplyId", stampList[pos].sealApplyId)
            intent.putExtra("macAddress", stampList[pos].sealEquipBlueToothMac)
            intent.putExtra("equipSn", stampList[pos].embenedSn)
            mContext.startActivity(intent)
        } else {
            ShowToast.shortTime("限时不支持")
        }
    }

    companion object {
        val instance: StampListFragment
            get() = StampListFragment()
    }
}
